#include "multicolumnfilterproxymodel.h"

MultiColumnFilterProxyModel::MultiColumnFilterProxyModel(QObject *parent)
    : QSortFilterProxyModel{parent}
{

}
void MultiColumnFilterProxyModel::setFilterPatterns(const QMap<int, QString> &patterns)
{
    m_filterPatterns.clear();
    for (auto it = patterns.begin(); it != patterns.end(); ++it) {
        m_filterPatterns[it.key()] = QRegularExpression(it.value(), QRegularExpression::CaseInsensitiveOption);
    }
    invalidateFilter();
}

void MultiColumnFilterProxyModel::setFilterPattern(const QVector<QStringList> &pattern)
{
    m_filterPattern.clear();
    m_filterPattern = pattern;
    invalidateFilter();
}

bool MultiColumnFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
//    for (auto it = m_filterPatterns.begin(); it != m_filterPatterns.end(); ++it) {
//        QModelIndex index = sourceModel()->index(sourceRow, it.key(), sourceParent);
//        if (!index.isValid())
//            continue;

//        QString value = index.data().toString();
//        if (!it.value().match(value).hasMatch())
//            return false;
//    }

    if (sourceParent.isValid())
    {
        qDebug()<<"无效的sourceParent";
        return false;
    }
    int colIdx;
    bool mr1=true,mr2=true,mr3=true,mr4=true;
    QString selStr ,filterType;
    QStringList qsl;
    //qDebug()<<m_filterPattern.size();
    for(int i=0;i<m_filterPattern.size();i++)
    {
        qsl= m_filterPattern.at(i);
        if(qsl.size()!=3)//参数个数不对
            continue;
        colIdx = qsl.at(0).toInt();
        selStr = qsl.at(1);
        filterType = qsl.at(2);
        //qDebug()<<colIdx<<selStr<<filterType;
        QModelIndex index = sourceModel()->index(sourceRow, colIdx, sourceParent);
        if (!index.isValid())
            continue;
        QString value = index.data().toString();
        //qDebug()<<colIdx<<selStr<<filterType<<value;
        if(filterType=="equal")
        {
            if(value=="-")
                mr1 = false;
            else
                mr1 = (value==selStr);
        }
        else if(filterType=="contains")
        {
            if(value=="-")
                mr2 = false;
            else
                mr2 = value.contains(selStr,Qt::CaseSensitive);
        }
        else if(filterType=="less")
        {
            if(value=="-")
                mr3 = false;
            else
                mr3 = (value<selStr);
        }
        else if(filterType=="more")
        {
            if(value=="-")
                mr4 = false;
            else
                mr4 = (value>selStr);
        }
        else
        {
            qDebug()<<"无效的filterType"<<filterType;
            return true;
        }


    }
    //qDebug()<<mr1<<mr2<<mr3<<mr4;
    return mr1&&mr2&&mr3&&mr4;
    //return true;
}
